package old.day20190318.dao;

import java.sql.*;

/**
 * @author DingZhenYun
 * @create 2019-03-20 16:59
 */
public class TestGetKey {
    public static void main(String[] args) {
        //取得数据库自动生成的主键
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try{
            connection=JDBCTools.getConnection();
            String sql="insert into t_users(username,password) values(?,?)";
            //使用重载的 prepareStatement(sql, flag)
            //来生成 PreparedStatement 对象
            preparedStatement=connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            preparedStatement.setString(1,"adfdfd1");
            preparedStatement.setString(2,"adfdfd1");
            preparedStatement.executeUpdate();
            //通过 getGeneratedKeys() 获取包含了新生成的主键的 ResultSet 对象
            //在 ResultSet 中只有一列 GENERATED_KEY, 用于存放新生成的主键值.
            ResultSet resultSet=preparedStatement.getGeneratedKeys();
            if(resultSet.next()){
                System.out.println(resultSet.getObject(1));
            }
            ResultSetMetaData rsmd=resultSet.getMetaData();
            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                System.out.println(rsmd.getColumnName(i+1));
            }
        }catch (Exception e){

        }finally {
            JDBCTools.release(preparedStatement,connection);
        }
    }
}
